package com.tusuo.stds.ui.splash;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.text.TextUtils;
import android.view.Gravity;

import com.flyco.animation.BaseAnimatorSet;
import com.flyco.animation.FadeEnter.FadeEnter;
import com.flyco.animation.FadeExit.FadeExit;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.tusuo.stds.MyApp;
import com.tusuo.stds.R;
import com.tusuo.stds.biz.CurrentUser;
import com.tusuo.stds.di.DaggerScope;
import com.tusuo.stds.di.Injector;
import com.tusuo.stds.rest.ApiHelper;
import com.tusuo.stds.rest.AppInfo;
import com.tusuo.stds.util.IntentUtils;
import com.tusuo.stds.util.Utils;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Fullscreen;
import org.androidannotations.annotations.res.StringRes;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import myandroid.library.util.ApplicationHelper;
import rx.Subscriber;

@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(SplashActivity.class)
@Fullscreen
@EActivity(R.layout.activity_splash)
public class SplashActivity extends Activity {

    private static final int APP_PERMISSION = 100;

    @Inject
    ApiHelper mApiHelper;
    @Inject
    CurrentUser mCurrentUser;

    @StringRes(R.string.err_msg_network_disabled)
    String mErrMsgNetworkDisabled;
    @StringRes(R.string.err_msg_server)
    String mErrMsgServer;

    private NormalDialog mDialog;

    Subscriber<AppInfo> mSubscriber;
    private boolean permissionTip = true;
    private NormalDialog permissionDialog;

    public void onResume() {
        super.onResume();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if(checkSelfPermission(Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(Manifest.permission.CHANGE_WIFI_STATE) != PackageManager.PERMISSION_GRANTED
                    ) {

                if (permissionTip) {
                    // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义)
                    requestPermissions(new String[]{
                            Manifest.permission.INTERNET,
                            Manifest.permission.READ_PHONE_STATE,
                            Manifest.permission.ACCESS_NETWORK_STATE,
                            Manifest.permission.ACCESS_WIFI_STATE,
                            Manifest.permission.CHANGE_WIFI_STATE
                    }, APP_PERMISSION);
                }
            } else {
                Injector.initSplashActivityComponent().inject(this);
                getAppInfo();
            }
        } else {
            Injector.initSplashActivityComponent().inject(this);
            getAppInfo();
        }
    }

    @Override
    protected void onDestroy() {
        if (mSubscriber != null) {
            mSubscriber.unsubscribe();
            mSubscriber = null;
        }
        if (mDialog != null) {
            mDialog.superDismiss();
            mDialog = null;
        }
        if (permissionDialog != null) {
            permissionDialog.superDismiss();
            permissionDialog = null;
        }
        super.onDestroy();
    }

    @Override public void onRequestPermissionsResult(int requestCode,String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions,grantResults);

        permissionTip = false;

        switch(requestCode)
        {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case APP_PERMISSION:
                boolean granted = true;
                for (int i : grantResults) {
                    if (i != PackageManager.PERMISSION_GRANTED) {
                        granted = false;
                        break;
                    }
                }

                if(!granted) {
                    // 没有获取到权限，做特殊处理
//                    Utils.UI.showToastLong("应用未赋予足够权限");
//                    delayToFinishApp();
                    showDisablePermissionDialog();
                }
                break;
            default:
                break;
        }
    }

    private void showDisablePermissionDialog() {
        permissionDialog = new NormalDialog(this);

        permissionDialog.isTitleShow(false)
                .btnNum(1)
                .bgColor(Color.parseColor("#FFFFFF"))
                .cornerRadius(5)
                .content("应用需要\"电话状态\"权限才能正常使用\n请在\"设置\"中开启权限")
                .contentGravity(Gravity.CENTER)
                .contentTextSize(13)
                .contentTextColor(Color.parseColor("#333333"))
                .dividerColor(Color.parseColor("#CCCCCC"))
                .btnText("确定")
                .btnTextSize(15.5f)
                .btnTextColor(Color.parseColor("#0092FF"))
                .widthScale(0.7f)
                .show();

        permissionDialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
//                        IntentUtils.toSystemPermissionActivity(mActivity);
                permissionDialog.dismiss();
                finish();
            }
        });

    }

    @Override
    public void onBackPressed() {}

    @Background(delay = 3000)
    void delayToFinishApp() {
        finish();
        ApplicationHelper.getInstance().exit();
    }

    @Background(delay = 2000)
    void delayToNextAction() {
        if (mCurrentUser.hasLoggedIn()) {
            IntentUtils.toMainActivity(SplashActivity.this);
        } else {
            IntentUtils.toLogin(SplashActivity.this);
        }

        finish();
    }

    void getAppInfo() {
        if (!Utils.Network.isNetworkAvailable()) {
            showNetworkDisabledDialog();
//            Utils.UI.showToastLong(mErrMsgNetworkDisabled);
//            delayToFinishApp();
            return;
        }

        mSubscriber = new AppInfoSubscriber();
        mApiHelper.getAppInfo(mSubscriber);
    }

    private void showNetworkDisabledDialog() {
        BaseAnimatorSet bas_in = new FadeEnter();
        BaseAnimatorSet bas_out = new FadeExit();
        mDialog = new NormalDialog(this);

        mDialog.isTitleShow(false)
                .btnNum(1)
                .bgColor(Color.parseColor("#FFFFFF"))
                .cornerRadius(5)
                .content("网络无连接,请检查网络连接后重试")
                .contentGravity(Gravity.CENTER)
                .contentTextSize(13)
                .contentTextColor(Color.parseColor("#333333"))
                .dividerColor(Color.parseColor("#CCCCCC"))
                .btnText("确定")
                .btnTextSize(15.5f, 15.5f)
                .btnTextColor(Color.parseColor("#0092FF"))
                .widthScale(0.7f)
                .showAnim(bas_in)
                .dismissAnim(bas_out)
                .show();

        mDialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                finish();
                ApplicationHelper.getInstance().exit();
            }
        });

    }

    private class AppInfoSubscriber extends Subscriber<AppInfo> {
        @Override
        public void onCompleted() {
            delayToNextAction();
        }

        @Override
        public void onError(Throwable e) {
            Utils.UI.showToastShort(mErrMsgServer);
            delayToFinishApp();
        }

        @Override
        public void onNext(AppInfo appInfo) {
            if (appInfo.checkState(SplashActivity.this)
                    && !TextUtils.isEmpty(appInfo.CookieName)
                    && !TextUtils.isEmpty(appInfo.UserStatus)) {
                mCurrentUser.setAppInfo(appInfo);
            } else {
                Utils.UI.showToastShort(mErrMsgServer);
                delayToFinishApp();
            }
        }
    }
}
